import { Component, OnInit } from '@angular/core';
import { AlertController,ToastController  } from '@ionic/angular';
import { Router, NavigationExtras } from '@angular/router';
import { DefaultLanguageService } from '@services/default-language.service';
import {TranslateService} from '@ngx-translate/core';
import { EventEmitterService,EventName } from '@services/event-emitter.service';
import { CommonService } from '@services/common-service.service';


@Component({
  selector: 'app-language',
  templateUrl: './language.page.html',
  styleUrls: ['./language.page.scss'],
})
export class LanguagePage implements OnInit {

  public name:string;

  public i18n:any = {};

  public languageList:Array<any> = [
    {
      code:'en_US',
      name:'English',
      checked:false,
      isShow:true
    },
    {
      code:'zh_CN',
      name:'Chinese',
      checked:false,
      isShow:true
    }
  ]

  constructor(private alertController: AlertController,
              private toastController:ToastController,
              private defaultLanguageService:DefaultLanguageService,
              private router: Router,
              private translate: TranslateService,
              private eventEmitterService:EventEmitterService,
              private commonService:CommonService) { 
    this.i18n = this.commonService.initTranslate(['myAccount.setting.language']); 
    let defaultLanguage = this.defaultLanguageService.getDefaultLanguage();
    this.languageList.forEach((item)=>{
      item.checked = (item.code == defaultLanguage);
    });
  }

  ngOnInit() {
  }

  searchLanguage(){
    if(this.name){
      this.languageList.forEach((item)=>{
        let languageName = item.name.toLocaleLowerCase();
        item.isShow = languageName.indexOf(this.name.toLocaleLowerCase())>-1;
      });
    }else{
      this.languageList.forEach((item)=>{
        item.isShow = true;
      });
    }
  }

  async selectLanguage(language){
    let defaultLanguage = this.defaultLanguageService.getDefaultLanguage();
    if(defaultLanguage == language.code){
      return false;
    } 
    const alert = await this.alertController.create({
      header: this.i18n.tip+' '+language.name+'?',
      buttons: [
        {
          text: this.i18n.cancel,
          role: 'cancel',
          cssClass: 'cancel-search',
          handler: () => {
            console.log('Confirm Cancel');
          }
        }, {
          text: this.i18n.confirm,
          handler: () => {
            this.defaultLanguageService.setDefaultLanguage(language.code);
            this.translate.setDefaultLang(language.code);
            this.translate.use(language.code);
            this.eventEmitterService.eventEmit.emit(EventName.EMAIL_CHANGED);
            this.languageList.forEach((item)=>{
              item.checked = (item.code == language.code);
            });
          }
        }
      ]
    });
    await alert.present();
  }

}
